package com.umessage.hotel.rest;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.umessage.common.service.RedisService;
import com.umessage.common.util.Atools;
import com.umessage.common.util.MD5Utils;
import com.umessage.common.util.QRCodeUtil;
import com.umessage.hotel.domain.BreakfastCoupon;
import com.umessage.hotel.domain.BreakfastRecord;
import com.umessage.hotel.model.BreakfastCouponQRCode;
import com.umessage.hotel.service.BreakfastCouponService;
import com.umessage.hotel.util.RestResult;
import com.umessage.hotel.util.RestResultGenerator;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 早餐优惠券管理
 * 
 * @author xiajh
 *
 */
@Api("早餐券管理")
@RestController
@EnableAutoConfiguration
@RequestMapping("/rest/breakfastcoupon")
public class BreakfastCouponResource {
	@Autowired
	private BreakfastCouponService breakfastCouponService;
	@Autowired
	private RedisService redisService;

	/**
	 *
	 */
	@ApiOperation(value = "今日早餐券列表", notes = "今日早餐券列表")
	@RequestMapping(value = "/today", method = RequestMethod.GET)
	public RestResult<List<BreakfastCoupon>> findBreakfastCoupons(ServletRequest request) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String date = sdf.format(new Date());
			String memberId = (String) request.getAttribute("subject");
			BreakfastCoupon coupon = new BreakfastCoupon();
			coupon.setMemberId(memberId);
			coupon.setValidDate(date);
			List<BreakfastCoupon> bfcs = this.breakfastCouponService.findBreakfastCouponsToday(coupon);
			return RestResultGenerator.genSuccessResult(bfcs);
		} catch (Exception e) {
			e.printStackTrace();
			return RestResultGenerator.genErrorResult(e.getMessage());
		}
	}

	/**
	 *
	 */
	@ApiOperation(value = "今日之后早餐券列表", notes = "今日之后早餐券列表")
	@RequestMapping(value = "/after", method = RequestMethod.GET)
	public RestResult<List<BreakfastCoupon>> findBreakfastCouponsAfter(ServletRequest request) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String date = sdf.format(new Date());
			String memberId = (String) request.getAttribute("subject");
			BreakfastCoupon coupon = new BreakfastCoupon();
			coupon.setMemberId(memberId);
			coupon.setValidDate(date);
			List<BreakfastCoupon> bfcs = this.breakfastCouponService.findBreakfastCouponsAfter(coupon);
			return RestResultGenerator.genSuccessResult(bfcs);
		} catch (Exception e) {
			e.printStackTrace();
			return RestResultGenerator.genErrorResult(e.getMessage());
		}
	}

	/**
	 *
	 */
	@ApiOperation(value = "历史早餐券列表", notes = "历史早餐券列表")
	@RequestMapping(value = "/history", method = RequestMethod.GET)
	public RestResult<List<BreakfastCoupon>> findBreakfastCouponsHistory(ServletRequest request) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String date = sdf.format(new Date());
			String memberId = (String) request.getAttribute("subject");
			BreakfastCoupon coupon = new BreakfastCoupon();
			coupon.setMemberId(memberId);
			coupon.setValidDate(date);
			List<BreakfastCoupon> bfcs = this.breakfastCouponService.findBreakfastCouponsHistory(coupon);
			return RestResultGenerator.genSuccessResult(bfcs);
		} catch (Exception e) {
			e.printStackTrace();
			return RestResultGenerator.genErrorResult(e.getMessage());
		}
	}

	@ApiOperation(value = "统计今日可用早餐券列表", notes = "统计今日可用早餐券列表")
	@RequestMapping(value = "/count", method = RequestMethod.GET)
	public RestResult<Integer> findBreakfastCouponsTodayCount(ServletRequest request) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String date = sdf.format(new Date());
			String memberId = (String) request.getAttribute("subject");
			BreakfastCoupon coupon = new BreakfastCoupon();
			coupon.setMemberId(memberId);
			coupon.setValidDate(date);
			Integer count = this.breakfastCouponService.findBreakfastCouponsTodayCount(coupon);
			return RestResultGenerator.genSuccessResult(count);
		} catch (Exception e) {
			e.printStackTrace();
			return RestResultGenerator.genErrorResult(e.getMessage());
		}
	}

	@ApiOperation(value = "获取早餐券使用二维码", notes = "获取早餐券使用二维码")
	@RequestMapping(value = "/{use_date}/{use_amount}/{member_id}/qrcode.png", method = RequestMethod.GET)
	public void getBreakfastCouponQRCode(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("use_date") String use_date, @PathVariable("use_amount") Integer use_amount,
			@PathVariable("member_id") String memberId) {
		try {
			JSONObject obj = new JSONObject();
			obj.put("mid", Atools.jiemi(memberId));
			obj.put("use_date", use_date);
			obj.put("use_amount", use_amount);
			obj.put("time_stamp", System.currentTimeMillis());
//			String  params = "mid="+obj.getString("mid") + "&time_stamp=" + obj.getString("time_stamp") + "&use_amount=" + "&use_date" + use_date; 
//			obj.put("sign", MD5Utils.encrypt(params));

			response.setContentType("image/png");
			response.setDateHeader("Expires", 0L);
			response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
			response.addHeader("Cache-Control", "post-check=0, pre-check=0");
			response.setHeader("Pragma", "no-cache");
			String data = Atools.jiami(obj.toJSONString());
			System.out.println("qrcode=" + data);
			QRCodeUtil.generateQRCode(data, 350, 350, "png", response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@ApiOperation(value = "使用早餐券", notes = "使用早餐券")
	@RequestMapping(value = "/useBreakfastCoupon", method = RequestMethod.GET)
	public RestResult<BreakfastCouponQRCode> useBreakfastCoupon(HttpServletRequest request,
			HttpServletResponse response, String use_date, Integer use_amount) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date useDate = sdf.parse(use_date);
			if (useDate == null) {
				RestResultGenerator.genErrorResult("invalid date format(yyyy-MM-dd)");
			}
			// TODO:判断是否有有足够的早餐券
			if (use_amount <= 0) {
				RestResultGenerator.genErrorResult(
						"invalid use_amount(notes: use_amount >= 0 and use_amount <= available tickets number)");
			}
			
			String memberId = (String) request.getAttribute("subject");
			BreakfastCouponQRCode qrcode = new BreakfastCouponQRCode();
			qrcode.setUseDate(use_date);
			qrcode.setUseAmount(use_amount);
			qrcode.setUrl("rest/breakfastcoupon/" + use_date + "/" + use_amount + "/" + Atools.jiami(memberId) + "/qrcode.png");

			return RestResultGenerator.genSuccessResult(qrcode);
		} catch (Exception e) {
			e.printStackTrace();
			return RestResultGenerator.genErrorResult(e.getMessage());
		}
	}

	/**
	 * 核销早餐券
	 */
	@ApiOperation(value = "核销早餐券", notes = "核销早餐券")
	@RequestMapping(value = "/cancelAfterVerification", method = RequestMethod.GET)
	public RestResult cancelAfterVerification(String data) {
		try {
			//String hotelId = (String) request.getAttribute("issuer");
			String source = Atools.jiemi(data);
			System.out.println("cancel after verification source =" + source);
			JSONObject qrcodeJson = JSONObject.parseObject(source);
			String memberId = qrcodeJson.getString("mid");
			String useDate = qrcodeJson.getString("use_date");
			Integer useAmount = qrcodeJson.getInteger("use_amount");
			String timeStamp = qrcodeJson.getString("time_stamp");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			if(System.currentTimeMillis()-30*60*1000L>Long.parseLong(timeStamp)) {
				return RestResultGenerator.genErrorResult("该二维码已过期!");
			}
			BreakfastCoupon coupon=new BreakfastCoupon();
			coupon.setValidDate(sdf.format(new Date()));
			coupon.setMemberId(memberId);
			Integer countNum=this.breakfastCouponService.countUseToday(coupon);
			if(useAmount>countNum) {
				return RestResultGenerator.genErrorResult("该二维码已过期!");
			}
			Date validDate = sdf.parse(useDate);
			String BCCache  = redisService.get(timeStamp+memberId);
			String BCData   = memberId+useDate+useAmount;
			
			if(BCCache != null && !"".equals(BCCache)){ 
				String[] BCCacheArray = BCCache.split(",");
				HashSet<String> set = new HashSet<String>();
				for (String str : BCCacheArray) {
					set.add(str);
				}
				if(!set.contains(BCData)){
					redisService.set(timeStamp+memberId, BCCache+","+BCData);
					// 开始核销
					BreakfastRecord useRecord = new BreakfastRecord();
					useRecord.setMemberId(memberId);
					useRecord.setValidDate(validDate);
					useRecord.setAmount(useAmount);
					breakfastCouponService.useBreakfastCoupon(useRecord);
					return RestResultGenerator.genSuccessResult(useRecord.getAmount());
				}else{
					return RestResultGenerator.genErrorResult("早餐券已经经过核销");
				}
			}else{
				redisService.set(timeStamp+memberId, BCData);
				// 开始核销
				BreakfastRecord useRecord = new BreakfastRecord();
				useRecord.setMemberId(memberId);
				useRecord.setValidDate(validDate);
				useRecord.setAmount(useAmount);
				breakfastCouponService.useBreakfastCoupon(useRecord);
				return RestResultGenerator.genSuccessResult(useRecord.getAmount());
			}
		} catch (Exception e) {
			e.printStackTrace();
			return RestResultGenerator.genErrorResult(e.getMessage());
		}
	}

	@ApiOperation(value = "早餐核销记录列表", notes = "早餐核销记录")
	@RequestMapping(value = "/checkRecord", method = RequestMethod.GET)
	public RestResult<List<BreakfastRecord>> checkRecord(HttpServletRequest request,
			@RequestParam(defaultValue = "1", required = true) int page,
			@RequestParam(defaultValue = "10", required = true) int rows) {
		try {
			String hotelId = (String) request.getAttribute("issuer");
			List<BreakfastRecord> breakfastRecord = this.breakfastCouponService.findRecords(hotelId, page, rows,null);
			return RestResultGenerator.genSuccessResult(breakfastRecord);
		} catch (Exception e) {
			e.printStackTrace();
			return RestResultGenerator.genErrorResult(e.getMessage());
		}
	}

}
